package com.hehanpeng.springbootapi.handler;

import com.hehanpeng.springbootapi.exception.InvalidRequestException;
import com.hehanpeng.springbootapi.exception.NotFoundException;
import com.hehanpeng.springbootapi.resource.ErrorResource;
import com.hehanpeng.springbootapi.resource.FieldResource;
import com.hehanpeng.springbootapi.resource.InvalidErrorResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hehanpeng
 * @date 2018/4/24 20:55
 */
@RestControllerAdvice
public class ApiExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler({NotFoundException.class})
    public ResponseEntity<?> handlerNotFound(RuntimeException e) {
        ErrorResource errorResource = new ErrorResource(e.getMessage());
        ResponseEntity result = new ResponseEntity<>(errorResource, HttpStatus.NOT_FOUND);
        logger.warn("Return ---------- {}", result);
        return result;
    }

    @ExceptionHandler({InvalidRequestException.class})
    public ResponseEntity<?> handlerInvalidRequest(InvalidRequestException e) {
        Errors errors = e.getErrors();
        List<FieldResource> fieldResources = new ArrayList<>();
        List<FieldError> fieldErrors = errors.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            FieldResource fieldResource = new FieldResource(fieldError.getObjectName(), fieldError.getField(), fieldError.getCode(), fieldError.getDefaultMessage());
            fieldResources.add(fieldResource);
        }
        InvalidErrorResource ier = new InvalidErrorResource(e.getMessage(), fieldResources);
        ResponseEntity result = new ResponseEntity<>(ier, HttpStatus.BAD_REQUEST);
        logger.warn("Return ---------- {}", result);
        return result;
    }

    /**
     * 处理全局异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler({Exception.class})
    public ResponseEntity<?> handlerException(Exception e) {
        logger.error("Error ---------- {}", e);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
